package com.customization.unionpay.market.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.engine.cube.biz.ShardingActionHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 未核销预付款结转台账按钮相关
 */
public class CarryoverOfUnverifiedButton {

    private static final Logger log = LoggerFactory.getLogger(CarryoverOfUnverifiedButton.class);


    /**
     * 根据唯一值查询未核销预付款结转台账数据
     *
     * @param maintablename
     * @param rq
     * @return
     */
    public static List<JSONObject> selectCarryoverOfUnverifiedBySth(String maintablename, String rq) {
        RecordSet rst = new RecordSet();
        String sql = "select id,jsrq from #{tableName} where rq = ? ";
        sql = sql.replace("#{tableName}", maintablename);
        log.info("sql：" + sql);
        rst.executeQuery(sql,rq);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("id", Util.null2String(rst.getString("id")));
            json.put("jsrq", Util.null2String(rst.getString("jsrq")));
            list.add(json);
        }
        return list;
    }

    /**
     * 根据ids查询未核销预付款结转台账数据
     *
     * @param maintablename
     * @param ids
     * @return
     */
    public static List<JSONObject> selectCarryoverOfUnverifiedByIds(String maintablename, String ids,String field) {

        ids = ids.replace(",","','");
        log.info("ids:"+ids);

        RecordSet rst = new RecordSet();
        String sql = "select id,rq from #{tableName} where id in ('"+ids+"') and ("+field+" is null or "+field+"='')";
        sql = sql.replace("#{tableName}", maintablename);
        log.info("sql：" + sql);
        rst.executeQuery(sql);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("id", Util.null2String(rst.getString("id")));
            json.put("rq", Util.null2String(rst.getString("rq")));
            list.add(json);
        }
        return list;
    }

    /**
     * 添加未核销预付款结转台账数据
     *
     * @param formId
     * @param formmodeId
     * @param maintablename
     * @param user
     * @param rq 日期
     * @param yrzje 已入账金额
     * @param yhxje 已核销金额
     * @param dhxje 待核销金额
     * @param jsrq 结算日期
     * @param cxrq 冲销日期
     * @param zt 状态
     *
     */
    public static void addCarryoverOfUnverifiedByFormId(int formId, int formmodeId, String maintablename, User user, String rq, String yrzje, String yhxje, String dhxje, String jsrq, String cxrq, String zt) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        // 先调用内部方法新建一条数据，获取数据id
        int billid = FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

        try {
            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formId);

            // 根据当前信息使用id修改新建数据
            String updateSql = "update #{tableName} set rq=?, yrzje=?, yhxje=?, dhxje=?, jsrq=?, cxrq=?, zt=?, form_biz_id = ? where id = ? ";
            updateSql = updateSql.replace("#{tableName}", maintablename);
            log.info("修改sql：" + updateSql);
            rst.executeUpdate(updateSql,rq,yrzje,yhxje,dhxje,jsrq,cxrq,zt,formBizId,billid);

            // 提交事务
            rst.commit();

            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(user.getUID(), formmodeId, billid);

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            ClearFundButtonRelated.deleteByBillId(maintablename, billid);
            log.error("添加数据异常：" + e.getMessage());
        }
    }

    /**
     * 根据id修改未核销预付款结转台账
     *
     * @param maintablename
     * @param id
     * @param yrzje 已入账金额
     * @param yhxje 已核销金额
     * @param dhxje 待核销金额
     * @param jsrq 结算日期
     * @param cxrq 冲销日期
     * @param zt 状态
     */
    public static void updateCarryoverOfUnverifiedById(String maintablename, String id, String yrzje, String yhxje, String dhxje, String jsrq, String cxrq, String zt) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            // 根据当前信息使用id修改新建数据
            StringBuilder updateSql = new StringBuilder();
            updateSql.append("update ");
            updateSql.append(maintablename);
            updateSql.append(" set ");
            if(StrUtil.isNotBlank(yhxje)){
                updateSql.append(" yhxje='");
                updateSql.append(yhxje);
            }
            if(StrUtil.isNotBlank(yrzje)){
                updateSql.append("', ");
                updateSql.append(" yrzje='");
                updateSql.append(yrzje);
            }
            if(StrUtil.isNotBlank(dhxje)){
                updateSql.append("', ");
                updateSql.append(" dhxje='");
                updateSql.append(dhxje);
            }
            if(StrUtil.isNotBlank(jsrq)){
                updateSql.append("', ");
                updateSql.append(" jsrq='");
                updateSql.append(jsrq);
            }
            if(StrUtil.isNotBlank(cxrq)){
                updateSql.append("', ");
                updateSql.append(" cxrq='");
                updateSql.append(cxrq);
            }
            if(StrUtil.isNotBlank(zt)){
                updateSql.append("', ");
                updateSql.append(" zt='");
                updateSql.append(zt);
            }
            updateSql.append("' ");
            updateSql.append(" where id = '");
            updateSql.append(id);
            updateSql.append("' ");

            log.info("updateSql: "+updateSql.toString());
            rst.executeUpdate(updateSql.toString());

            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常：" + e.getMessage());
        }
    }

    /**
     * 查询核销报账流程对应月份的id，本次核销金额汇总相关信息
     * @param TODO 表名写死（注意）
     * @param rzrq 入账日期
     * @return
     */
    public static List<JSONObject> selectVerificationReimbursementByRzrq(String rzrq,String maintablename) {
        log.info("rzrq："+rzrq);
        List<JSONObject> list = new ArrayList<>();
        RecordSet rst = new RecordSet();
        // 供应商编号 营销事项申请单号 本次核销金额 经济事项
        String sql = " select " +
                " f225.gysbh gysbh," +
                " dt3.sqdh ysxsqd," +
                " dt1.bchxje bchxje," +
                " dt1.jjsx jjsx " +
                " from formtable_main_225 f225 " +
                " join formtable_main_225_dt1 dt1 " +
                " on dt1.mainid = f225.id " +
                " join "+maintablename+" dt3 " +
                " on dt3.id = dt1.ysxsqd " +
                " where date_format(f225.rzrq,'%Y-%m') = ? ";
        log.info("selectVerificationReimbursementByRzrq:"+sql);
        rst.executeQuery(sql,rzrq);
        while (rst.next()) {
            log.info("in rst next！");
            JSONObject json = new JSONObject();
            json.put("gysbh", Util.null2String(rst.getString("gysbh")));
            json.put("ysxsqd", Util.null2String(rst.getString("ysxsqd")));
            json.put("bchxje", Util.null2String(rst.getString("bchxje")));
            json.put("jjsx", Util.null2String(rst.getString("jjsx")));
            list.add(json);
        }
        return list;
    }

    /**
     * 查询核销报账流程对应月份的营销事项申请单号，本次核销金额等相关信息
     * @param tn1 营销活动事项台账表名
     * @param tn2 营销日报表台账表名
     * @param codes 营销平台事项申请单号
     * @return
     */
    public static List<JSONObject> selectVerificationReimbursementBySth(String tn1,String tn2,String codes,String selectValueNormalData,String selectValueApprovedChangeData,String isNot) {
        RecordSet rst = new RecordSet();
        // 营销活动事项台账 营销平台事项申请单号 营销平台活动授权码	 财务是否结束	 公司       部门 是否为大协议 合同编号 活动类型 资金来源 已入账金额
        // 营销日报表台账  营销平台事项申请单号 营销平台活动授权码    日报流水类型   入账批次号
        String sql = " select " +
                    " tn1.sqdh sqdh," +
                    " tn1.yxpthdsqm yxpthdsqm," +
                    " tn1.cwsfjs cwsfjs," +
                    " tn1.gs gs," +
                    " tn1.bm bm," +
                    " tn1.sfwdxy sfwdxy," +
                    " tn1.htbh htbh," +
                    " tn1.ACT_TP ACT_TP," +
                    " tn1.zjly zjly," +
                    " tn1.yrzje yrzje," +
                    " tn2.rzpch rzpch " +
                    " from "+tn1+" as tn1 " +
                    " join "+tn2+" as tn2 "+
                    " on tn1.yxpthdsqm = tn2.yxpthdsqm "+
                    " where tn1.sqdh in ('"+codes+"') and (tn2.rblslx='"+selectValueNormalData+"' or tn2.rblslx='"+selectValueApprovedChangeData+"') and tn1.cwsfjs='"+isNot+"' ";
        log.info("selectVerificationReimbursementBySth:"+sql);
        rst.executeQuery(sql);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("sqdh", Util.null2String(rst.getString("sqdh")));
            json.put("yxpthdsqm", Util.null2String(rst.getString("yxpthdsqm")));
            json.put("cwsfjs", Util.null2String(rst.getString("cwsfjs")));
            json.put("gs", Util.null2String(rst.getString("gs")));
            json.put("bm", Util.null2String(rst.getString("bm")));
            json.put("sfwdxy", Util.null2String(rst.getString("sfwdxy")));
            json.put("htbh", Util.null2String(rst.getString("htbh")));
            json.put("ACT_TP", Util.null2String(rst.getString("ACT_TP")));
            json.put("zjly", Util.null2String(rst.getString("zjly")));
            json.put("yrzje", Util.null2String(rst.getString("yrzje")));
            json.put("rzpch", Util.null2String(rst.getString("rzpch")));
            list.add(json);
        }
        return list;
    }

    /**
     * 累加字符串
     * @param numberIc
     * @return
     * @throws Exception
     */
    public static String sumStrNumber(List<String> numberIc) throws Exception {
        // 初始化总和为0
        double sum = 0.0;

        // 遍历列表并累加数值
        for (String str : numberIc) {
            try {
                // 将字符串转换为 double 类型并累加
                double number = Double.parseDouble(str);
                sum += number;
            } catch (NumberFormatException e) {
                // 处理非数值字符串的情况，可以输出错误信息或者进行其他处理
               throw new Exception("非法字符串！");
            }
        }
        return String.valueOf(sum);
    }

    /**
     * 拼接字符串
     * @param strings
     * @return
     */
    public static String changeListStr(List<String> strings){
        String result = "";

        // 遍历列表并将每个元素添加到结果字符串中
        for (int i = 0; i < strings.size(); i++) {
            result += "'" + strings.get(i) + "'";
            if (i != strings.size() - 1) {
                result += ",";
            }
        }

        return result;
    }



}
